#!/bin/sh

# If this script returns non-zero or times out then the xHA daemon will attempt to restart xapi

RETVAL=1 # Exit code 1 indicates a communication failure which could be temporary if a master transition is happening (CA-17697)
ATTEMPTS=20 # Max number of times to retry given a temporary communication failure (with 5 second pauses between)

N=0

while true; do
  N=$(expr $N + 1)
  # On any result other than temporary communication failure, exit immediately
  if [ $RETVAL -ne 1 ]; then
   exit $RETVAL 
  fi
  # Fail altogether if we exceed our max attempts threshold
  if [ $N -gt $ATTEMPTS ]; then
   exit 1
  fi

  xe host-ha-xapi-healthcheck >/dev/null 2>&1
  RETVAL=$?

  # If a temporary communication failure, sleep for 1s before trying again
  if [ $RETVAL -eq 1 ]; then 
   echo -n "."
   sleep 5
  fi
done
